//
//  AppLovinCocosSDK.swift
//  Game105Client-mobile
//
//  Created by Developer001 on 2025/3/27.
//

import Foundation
import AppLovinSDK

@objc class AppLovinCocosSDK : NSObject, SDKDelegate, MAAdDelegate, MARewardedAdDelegate, MAAdViewAdDelegate, MAAdRevenueDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: AppLovinCocosSDK?
    
    var viewController :UIViewController?
    
    let sdkKey = "9uHgeBwag3NXva9MC23ToO3q11Ve59bF1uwg4qGltdGmCQ7OSByFZ_3b1ZF7krMlkHQo5gXzIokVDsvg1rwbr-";
    let interstitialAdUnitId = "b208842e6e617466";
    let rewardedAdUnitId = "2fccc1562e7977f1";
    let bannerAdUnitId = "1b83a60ac8976ccd";
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@AppLovinCocosSDK launched")
        
        AppLovinCocosSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        JsbSDK.onMsg("AppLovinCocosSDK.showMediationDebugger", handler: self.showMediationDebugger);
        
        JsbSDK.onMsg("AppLovinCocosSDK.createInterstitialAd", handler: self.createInterstitialAd);
        JsbSDK.onMsg("AppLovinCocosSDK.showInterstitialAd", handler: self.showInterstitialAd);
        JsbSDK.onMsg("AppLovinCocosSDK.isReadyInterstitialAd", handler: self.isReadyInterstitialAd);
        
        
        JsbSDK.onMsg("AppLovinCocosSDK.createRewardedAd", handler: self.createRewardedAd);
        JsbSDK.onMsg("AppLovinCocosSDK.showRewardedAd", handler: self.showRewardedAd);
        JsbSDK.onMsg("AppLovinCocosSDK.isReadyRewardedAd", handler: self.isReadyRewardedAd);
        
        JsbSDK.onMsg("AppLovinCocosSDK.createBannerAd", handler: self.createBannerAd);
        JsbSDK.onMsg("AppLovinCocosSDK.hideBannerAd", handler: self.hideBannerAd);
        JsbSDK.onMsg("AppLovinCocosSDK.removeBannerAd", handler: self.removeBannerAd);
        
        initialize()
        return true
    }
    
    func initialize() {
        let initConfig = ALSdkInitializationConfiguration(sdkKey: sdkKey) { builder in
            builder.mediationProvider = ALMediationProviderMAX
//            builder.testDeviceAdvertisingIdentifiers = ["1F541BC0-0CA5-4ED3-995A-955798A6B3D4"] // iPhone12开发机
        }
        
//        let settings = ALSdk.shared().settings
//        settings.termsAndPrivacyPolicyFlowSettings.isEnabled = true
//        settings.termsAndPrivacyPolicyFlowSettings.termsOfServiceURL = URL(string: "https://pogorockgames.com/hikeepetaltrip.html")
//        settings.termsAndPrivacyPolicyFlowSettings.privacyPolicyURL = URL(string: "https://pogorockgames.com/hikeeprivacy.html")
//        settings.isVerboseLoggingEnabled = true
        
//        ALSdk.shared().settings.isMuted = true;
        
        ALSdk.shared().initialize(with: initConfig) { sdkConfig in
            // Start loading ads
        }
        
    }
    
    func showMediationDebugger(args:String?) {
        print("@showMediationDebugger")
        ALSdk.shared().showMediationDebugger()
    }
    
    // interstitial ad
    var interstitialAd: MAInterstitialAd!
    var interstitialRetryAttempt = 0.0
    
    var rewardedAd: MARewardedAd!
    var rewardedRetryAttempt = 0.0
    

    // 加载插屏广告
    func createInterstitialAd(args:String?) {
        interstitialAd = MAInterstitialAd(adUnitIdentifier: interstitialAdUnitId)
        interstitialAd.delegate = self

        // Load the first ad
        interstitialAd.load()
        JsbSDK.sendMsg("AppLovinCocosSDKManager.load_InterstitialAd", args: [:])
    }
    
    func createRewardedAd(args:String?) {
        rewardedAd = MARewardedAd.shared(withAdUnitIdentifier: rewardedAdUnitId)
        rewardedAd.delegate = self
        rewardedAd.load()
        JsbSDK.sendMsg("AppLovinCocosSDKManager.load_RewardedAd", args: [:])
    }

    // MARK: MAAdDelegate Protocol

    func didLoad(_ ad: MAAd) {
        print("@didLoad", ad);
        let adUnit: String = ad.adUnitIdentifier
        if ad.format == MAAdFormat.interstitial {
            interstitialRetryAttempt = 0
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didLoad_InterstitialAd", args: [
                "adUnitIdentifier": adUnit
            ])
        } else if ad.format == MAAdFormat.rewarded {
            rewardedRetryAttempt = 0
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didLoad_RewardedAd", args: [
                "adUnitIdentifier": adUnit
            ])
        } else if ad.format == MAAdFormat.banner {
            bannerRetryAttempt = 0
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didLoad_BannerAd", args: [
                "adUnitIdentifier": adUnit
            ])
        }
    }

    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        // Interstitial ad failed to load
        // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds)
        
        if adUnitIdentifier == interstitialAdUnitId {
            interstitialRetryAttempt += 1
            let delaySec = pow(2.0, min(6.0, interstitialRetryAttempt))
            DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
                AppLovinCocosSDK.instance?.interstitialAd.load()
                JsbSDK.sendMsg("AppLovinCocosSDKManager.load_InterstitialAd", args: [:])
            }
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFailToLoadAd_InterstitialAd", args: [
                "adUnitIdentifier": adUnitIdentifier,
                "errMessage": error.message,
            ])
        } else if adUnitIdentifier == rewardedAdUnitId {
            rewardedRetryAttempt += 1
            let delaySec = pow(2.0, min(6.0, rewardedRetryAttempt))
            DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
                AppLovinCocosSDK.instance?.rewardedAd.load()
                JsbSDK.sendMsg("AppLovinCocosSDKManager.load_RewardedAd", args: [:])
            }
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFailToLoadAd_RewardedAd", args: [
                "adUnitIdentifier": adUnitIdentifier,
                "errMessage": error.message
            ])
        } else if adUnitIdentifier == bannerAdUnitId {
            bannerRetryAttempt += 1
            // banner 不需要在这里重试
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFailToLoadAd_BannerAd", args: [
                "adUnitIdentifier": adUnitIdentifier,
                "errMessage": error.message
            ])
        }
    }

    func didDisplay(_ ad: MAAd) {
        print("@didDisplay", ad);
        if ad.format == MAAdFormat.interstitial {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didDisplay_InterstitialAd", args: ["networkName": ad.networkName])
        } else if ad.format == MAAdFormat.rewarded {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didDisplay_RewardedAd", args: ["networkName": ad.networkName])
        } else if ad.format == MAAdFormat.banner {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didDisplay_BannerAd", args: ["networkName": ad.networkName])
        }
    }

    func didClick(_ ad: MAAd) {
        print("@didClick", ad);
        if ad.format == MAAdFormat.interstitial {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didClick_InterstitialAd", args: [:])
        } else if ad.format == MAAdFormat.rewarded {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didClick_RewardedAd", args: [:])
        } else if ad.format == MAAdFormat.banner {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didClick_BannerAd", args: [:])
        }
    }

    func didHide(_ ad: MAAd) {
        // Interstitial ad is hidden. Pre-load the next ad
        if ad.format == MAAdFormat.interstitial {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didHide_InterstitialAd", args: ["networkName": ad.networkName])
            interstitialAd.load()
            JsbSDK.sendMsg("AppLovinCocosSDKManager.load_InterstitialAd", args: [:])
        } else if ad.format == MAAdFormat.rewarded {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didHide_RewardedAd", args: ["networkName": ad.networkName])
            rewardedAd.load()
            JsbSDK.sendMsg("AppLovinCocosSDKManager.load_RewardedAd", args: [:])
        } else if ad.format == MAAdFormat.banner {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didHide_BannerAd", args: ["networkName": ad.networkName])
        }
    }

    func didFail(toDisplay ad: MAAd, withError error: MAError) {
        // Interstitial ad failed to display. AppLovin recommends that you load the next ad.
        print("didFail \(error.code) \(error.message)")
        if ad.format == MAAdFormat.interstitial {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFail_InterstitialAd", args: ["code": error.code, "message": error.message])
            interstitialAd.load()
            JsbSDK.sendMsg("AppLovinCocosSDKManager.load_InterstitialAd", args: [:])
        } else if ad.format == MAAdFormat.rewarded {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFail_RewardedAd", args: ["code": error.code, "message": error.message])
            rewardedAd.load()
            JsbSDK.sendMsg("AppLovinCocosSDKManager.load_RewardedAd", args: [:])
        } else if ad.format == MAAdFormat.banner {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didFail_BannerAd", args: ["code": error.code, "message": error.message])
        }
    }
    
    func didRewardUser(for ad: MAAd, with reward: MAReward) {
        if ad.format == MAAdFormat.rewarded {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.didRewardUser_RewardedAd", args: ["label":reward.label, "amount":reward.amount, "description":reward.description])
        }
    }
    
    // 展示插屏广告
    func showInterstitialAd(args: String?) {
        if interstitialAd.isReady {
            interstitialAd.show()
        }
    }
    
    func isReadyInterstitialAd(args: String?) {
        if interstitialAd.isReady {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.isReadyInterstitialAd", args: ["isReady": true])
        } else {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.isReadyInterstitialAd", args: ["isReady": false])
        }
    }
    
    // 展示激励广告
    func showRewardedAd(args: String?) {
        if (rewardedAd.isReady) {
            rewardedAd.show()
        }
    }
    
    func isReadyRewardedAd(args: String?) {
        if (rewardedAd.isReady) {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.isReadyRewardedAd", args: ["isReady": true])
        } else {
            JsbSDK.sendMsg("AppLovinCocosSDKManager.isReadyRewardedAd", args: ["isReady": false])
        }
    }

    func didPayRevenue(for ad: MAAd) {
        print("@didPayRevenue adUnitIdentifier", ad.adUnitIdentifier)
        
        let maxCountryCode: String = ALSdk.shared().configuration.countryCode
        let countryCode: String = maxCountryCode.isEmpty ? "" : maxCountryCode
        let adUnit: String = ad.adUnitIdentifier
        let placement: String = ad.placement ?? "default"
        let adNetwork: String = ad.networkName
        let revenue: NSNumber = NSNumber(value: ad.revenue)
        let precision: String = ad.revenuePrecision
        let adFormat: String = ad.format.label
        
        JsbSDK.sendMsg("AppLovinCocosSDKManager.didPayRevenue", args: [
            "adUnitIdentifier": adUnit,
            "placement": placement,
            "networkName": adNetwork,
            "revenue": revenue,
            "revenuePrecision": precision,
            "countryCode": countryCode,
            "adFormat": adFormat
        ]);
    }
    
    // 展示横幅广告
    var adView: MAAdView!
    var bannerRetryAttempt = 0.0
    @MainActor
    func createBannerAd(args: String?) {
        print("@createBannerAd")
        if adView == nil {
            adView = MAAdView(adUnitIdentifier: bannerAdUnitId, adFormat: MAAdFormat.banner)
            adView.delegate = self
            let height: CGFloat = (UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50
            let width = UIScreen.main.bounds.width
            let x: CGFloat = 0
            let y: CGFloat = UIScreen.main.bounds.height - CGFloat(height)
            adView.frame = CGRect(x: x, y: y, width: width, height: height)
            adView.backgroundColor = .clear
            viewController?.view.addSubview(adView)
            adView.loadAd()
            JsbSDK.sendMsg("AppLovinCocosSDKManager.load_BannerAd", args: [:])
        } else {
            viewController?.view.addSubview(adView)
        }
    }
    
    @MainActor
    func hideBannerAd(args: String?) {
        print("@hideBannerAd")
        if adView != nil {
            adView.removeFromSuperview()
        }
    }
    
    @MainActor
    func removeBannerAd(args: String?) {
        print("@removeBannerAd")
        if adView != nil {
            adView.removeFromSuperview()
            adView.delegate = nil
            adView = nil
        }
    }
    
    func didExpand(_ ad: MAAd) {
        print("@didExpand \(ad)")
    }
    
    func didCollapse(_ ad: MAAd) {
        print("@didCollapse \(ad)")
    }
}
